package net.stock.service;

import net.stock.db.UserAccess;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.jdo.JDOObjectNotFoundException;
import java.util.List;
import java.util.Collection;

/**
 * @author naim
 * @date Dec 27, 2009
 */
public class RequestJdoDao extends JdoDaoSupport implements RequestDao {

    public void save(UserAccess ua) {
        PersistenceManager pm = getPersistenceManager();
        try {
            pm.makePersistent(ua);
        } finally {
            releasePersistenceManager(pm);
        }
    }

    public UserAccess getUserAccess(String email) {
        PersistenceManager pm = getPersistenceManager();
        try {
            return pm.getObjectById(UserAccess.class, email);
        } catch (JDOObjectNotFoundException e) {
            return null;
        } finally {
            releasePersistenceManager(pm);
        }
    }

    public Collection<UserAccess> getPendingRequests() {
        return getFromUserAccess(false);
    }

    public Collection<UserAccess> getApprovedRequests() {
        return getFromUserAccess(true);
    }

    private Collection<UserAccess> getFromUserAccess(boolean hasAccess) {
        PersistenceManager pm = getPersistenceManager();
        Query query = pm.newQuery(UserAccess.class, "hasAccess == " + hasAccess);
        try {
            return pm.detachCopyAll( (Collection<UserAccess>) query.execute() );
        } finally {
            releasePersistenceManager(pm);
        }
    }

    public void allowAccess(List<String> emailAddressList) {
        setAccess(emailAddressList, true);
    }

    public void denyAccess(List<String> emailAddressList) {
        setAccess(emailAddressList, false);
    }

    private void setAccess(List<String> emailAddressList, boolean access) {
        PersistenceManager pm = getPersistenceManager();
        Query query = pm.newQuery(UserAccess.class, ":p.contains(email)");
        try {
            Collection<UserAccess> uaList = (Collection<UserAccess>) query.execute(emailAddressList);
            for (UserAccess ua : uaList) {
                ua.setHasAccess(access);
            }
        } finally {
            releasePersistenceManager(pm);
        }
    }
}
